package cn.by.wms.service;

import cn.by.wms.dao.UserRoleDao;
import cn.by.wms.entity.Roles;
import cn.by.wms.entity.User;
import cn.by.wms.entity.UserQuery;
import cn.by.wms.entity.UserRole;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class UserRoleService {
    @Autowired
    private UserRoleDao userRoleDao;
    @Autowired
    private UserService userService;

    public Integer insert(UserRole userRole) {
        // 拿到用户ID以及用户需要增加的用户权限ID
        Integer userId = userRole.getUserId();
        //用户需要添加的角色ID
        List<Integer> addRoleIds = userRole.getRoleIds();

        // 查询用户的信息ID
        List<User> users = userService.select(new UserQuery().setId(userId));
        List<Roles> roles = users.get(0).getRoles();
        //用户全部的角色ID
        List<Integer> allRoleIds = roles.stream().map(Roles::getId).collect(Collectors.toList());
        //从addRoleIds中过滤掉用户已有的角色ID
        List<Integer> addRoleIds2 = addRoleIds.stream().filter(id -> !allRoleIds.contains(id)).collect(Collectors.toList());
        if (addRoleIds2.size() > 0) {
            // 批量添加
            userRole.setRoleIds(addRoleIds2);
            UserRoleService userRoleService = (UserRoleService) (AopContext.currentProxy());
            userRoleService.addRole(userRole);
        }
        System.out.println(addRoleIds2);
        return 0;
    }
    @Transactional
    public void addRole(UserRole userRole){
        userRoleDao.insert(userRole);
    }

    public List<Roles> selectRole(Roles roles){
      return userRoleDao.selectRole(roles);
  }
  public  Integer delete(UserRole userRole){
      return userRoleDao.delete(userRole);
  }


}
